# -*- coding: utf-8 -*-
"""
评价视图

包含评价系统的所有页面和API：
- 评价列表
- 创建评价
- 评价详情
- 修改评价
- 评价统计
- 待评价列表
"""

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from datetime import datetime, date, timedelta

from app.decorators import student_required, coach_required
from app.controllers.evaluation_controller import EvaluationController
from app.forms.evaluation_forms import (
    EvaluationForm, EditEvaluationForm, EvaluationFilterForm,
    QuickEvaluationForm
)

# 创建评价蓝图
evaluations_bp = Blueprint('evaluations', __name__)


@evaluations_bp.route('/')
@login_required
def index():
    """
    评价列表页面

    显示用户的所有评价，支持筛选和分页
    """
    # 确定用户类型
    user_type = 'student' if current_user.role == 'student' else 'coach'

    # 创建筛选表单
    filter_form = EvaluationFilterForm(user_id=current_user.id, user_type=user_type)

    # 获取筛选参数
    status = request.args.get('status', '')
    rating = request.args.get('rating', '')
    coach_id = request.args.get('coach_id', '')
    start_date = None
    end_date = None
    page = request.args.get('page', 1, type=int)

    # 解析日期参数
    if request.args.get('start_date'):
        try:
            start_date = datetime.strptime(request.args.get('start_date'), '%Y-%m-%d').date()
        except ValueError:
            pass

    if request.args.get('end_date'):
        try:
            end_date = datetime.strptime(request.args.get('end_date'), '%Y-%m-%d').date()
        except ValueError:
            pass

    try:
        # 获取评价列表
        result = EvaluationController.get_user_evaluations(
            user_id=current_user.id,
            user_type=user_type,
            page=page,
            per_page=10,
            status=status if status else None
        )

        if result['success']:
            evaluations = result['evaluations']
            pagination = result['pagination']
        else:
            flash('获取评价列表失败', 'error')
            evaluations = []
            pagination = None

    except Exception as e:
        flash(f'获取评价列表失败: {str(e)}', 'error')
        evaluations = []
        pagination = None

    # 获取待评价列表
    try:
        pending_evaluations = EvaluationController.get_pending_evaluations(
            user_id=current_user.id,
            user_type=user_type
        )
    except Exception:
        pending_evaluations = []

    # 设置表单默认值
    if request.method == 'GET':
        filter_form.status.data = status
        filter_form.rating.data = rating
        filter_form.coach_id.data = coach_id
        filter_form.start_date.data = start_date
        filter_form.end_date.data = end_date

    return render_template('evaluations/index.html',
                         evaluations=evaluations,
                         pagination=pagination,
                         pending_evaluations=pending_evaluations,
                         filter_form=filter_form,
                         user_type=user_type,
                         filter_params={
                             'status': status,
                             'rating': rating,
                             'coach_id': coach_id,
                             'start_date': start_date,
                             'end_date': end_date
                         })


@evaluations_bp.route('/create/<int:reservation_id>', methods=['GET', 'POST'])
@login_required
def create(reservation_id):
    """
    创建评价页面
    """
    # 确定用户类型
    user_type = 'student' if current_user.role == 'student' else 'coach'

    # 验证评价权限
    try:
        permission_result = EvaluationController.validate_evaluation_permission(
            reservation_id=reservation_id,
            user_id=current_user.id,
            user_type=user_type
        )

        if not permission_result['valid']:
            flash(permission_result['message'], 'error')
            return redirect(url_for('evaluations.index'))

        reservation = permission_result['reservation']

    except Exception as e:
        flash(f'验证评价权限失败: {str(e)}', 'error')
        return redirect(url_for('evaluations.index'))

    form = EvaluationForm(reservation=reservation, user_type=user_type)

    if form.validate_on_submit():
        try:
            result = EvaluationController.create_evaluation(
                reservation_id=reservation_id,
                evaluator_id=current_user.id,
                evaluator_type=user_type,
                rating=int(form.rating.data),
                comment=form.comment.data
            )

            if result['success']:
                flash('评价提交成功！', 'success')
                return redirect(url_for('evaluations.detail',
                                      evaluation_id=result['evaluation_id']))
            else:
                flash(result.get('message', '评价提交失败'), 'error')

        except Exception as e:
            flash(f'提交评价失败: {str(e)}', 'error')

    return render_template('evaluations/create.html',
                         form=form,
                         reservation=reservation,
                         user_type=user_type)


@evaluations_bp.route('/detail/<int:evaluation_id>')
@login_required
def detail(evaluation_id):
    """
    评价详情页面
    """
    try:
        result = EvaluationController.get_evaluation_detail(
            evaluation_id=evaluation_id,
            user_id=current_user.id
        )

        if not result['success']:
            flash(result.get('message', '获取评价详情失败'), 'error')
            return redirect(url_for('evaluations.index'))

        evaluation_data = result

    except Exception as e:
        flash(f'获取评价详情失败: {str(e)}', 'error')
        return redirect(url_for('evaluations.index'))

    return render_template('evaluations/detail.html',
                         evaluation_data=evaluation_data)


@evaluations_bp.route('/edit/<int:evaluation_id>', methods=['GET', 'POST'])
@login_required
def edit(evaluation_id):
    """
    修改评价页面
    """
    # 确定用户类型
    user_type = 'student' if current_user.role == 'student' else 'coach'

    try:
        # 获取评价详情
        detail_result = EvaluationController.get_evaluation_detail(
            evaluation_id=evaluation_id,
            user_id=current_user.id
        )

        if not detail_result['success']:
            flash(detail_result.get('message', '获取评价详情失败'), 'error')
            return redirect(url_for('evaluations.index'))

        evaluation = detail_result['evaluation']

        # 检查是否可以修改
        can_modify = False
        if user_type == 'student':
            can_modify = detail_result.get('can_modify_student', False)
        else:
            can_modify = detail_result.get('can_modify_coach', False)

        if not can_modify:
            flash('评价已超过修改时限（24小时）或您无权修改此评价', 'error')
            return redirect(url_for('evaluations.detail', evaluation_id=evaluation_id))

    except Exception as e:
        flash(f'获取评价信息失败: {str(e)}', 'error')
        return redirect(url_for('evaluations.index'))

    form = EditEvaluationForm(evaluation=evaluation, user_type=user_type)

    if form.validate_on_submit():
        try:
            result = EvaluationController.update_evaluation(
                evaluation_id=evaluation_id,
                user_id=current_user.id,
                user_type=user_type,
                rating=int(form.rating.data),
                comment=form.comment.data
            )

            if result['success']:
                flash('评价更新成功！', 'success')
                return redirect(url_for('evaluations.detail', evaluation_id=evaluation_id))
            else:
                flash(result.get('message', '评价更新失败'), 'error')

        except Exception as e:
            flash(f'更新评价失败: {str(e)}', 'error')

    return render_template('evaluations/edit.html',
                         form=form,
                         evaluation=evaluation,
                         user_type=user_type)


@evaluations_bp.route('/pending')
@login_required
def pending():
    """
    待评价列表页面
    """
    # 确定用户类型
    user_type = 'student' if current_user.role == 'student' else 'coach'

    try:
        pending_evaluations = EvaluationController.get_pending_evaluations(
            user_id=current_user.id,
            user_type=user_type
        )
    except Exception as e:
        flash(f'获取待评价列表失败: {str(e)}', 'error')
        pending_evaluations = []

    return render_template('evaluations/pending.html',
                         pending_evaluations=pending_evaluations,
                         user_type=user_type)


@evaluations_bp.route('/quick-evaluate', methods=['POST'])
@login_required
def quick_evaluate():
    """
    快速评价API（AJAX）
    """
    form = QuickEvaluationForm()

    if form.validate_on_submit():
        try:
            user_type = 'student' if current_user.role == 'student' else 'coach'

            result = EvaluationController.create_evaluation(
                reservation_id=int(form.reservation_id.data),
                evaluator_id=current_user.id,
                evaluator_type=user_type,
                rating=int(form.rating.data),
                comment=form.comment.data
            )

            if result['success']:
                return jsonify({
                    'success': True,
                    'message': '评价提交成功',
                    'evaluation_id': result['evaluation_id']
                })
            else:
                return jsonify({
                    'success': False,
                    'message': result.get('message', '评价提交失败')
                })

        except Exception as e:
            return jsonify({
                'success': False,
                'message': f'提交评价失败: {str(e)}'
            })
    else:
        errors = []
        for field, error_list in form.errors.items():
            errors.extend(error_list)
        return jsonify({
            'success': False,
            'message': '表单验证失败: ' + '; '.join(errors)
        })


@evaluations_bp.route('/api/get-evaluation-data/<int:evaluation_id>')
@login_required
def get_evaluation_data(evaluation_id):
    """
    获取评价数据API（用于前端图表）
    """
    try:
        result = EvaluationController.get_evaluation_detail(
            evaluation_id=evaluation_id,
            user_id=current_user.id
        )

        if result['success']:
            evaluation = result['evaluation']
            return jsonify({
                'success': True,
                'data': {
                    'student_rating': evaluation.student_rating,
                    'coach_rating': evaluation.coach_rating,
                    'student_comment': evaluation.student_comment,
                    'coach_comment': evaluation.coach_comment,
                    'is_completed': evaluation.is_completed(),
                    'created_at': evaluation.created_at.isoformat() if evaluation.created_at else None
                }
            })
        else:
            return jsonify({
                'success': False,
                'message': result.get('message', '获取评价数据失败')
            })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取评价数据失败: {str(e)}'
        })


# 错误处理
@evaluations_bp.errorhandler(404)
def not_found_error(error):
    """处理404错误"""
    return render_template('errors/404.html'), 404


@evaluations_bp.errorhandler(500)
def internal_error(error):
    """处理500错误"""
    return render_template('errors/500.html'), 500